package cn.player.view;

import android.content.Context;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by DD_ZGL on 2016/3/29.
 */
public class ViewHolder {
    private int mPosition;
    private SparseArray<View> mViews;
    private View mConvertView;

    public ViewHolder(Context context, int layoutId, int position) {
        this.mPosition = position;
        mViews = new SparseArray<>();
        mConvertView = View.inflate(context, layoutId, null);
        mConvertView.setTag(this);
    }

    public static ViewHolder getInstance(Context context, View convertView, int layoutId, int position) {
        if (convertView == null) {
            return new ViewHolder(context, layoutId, position);
        } else {
            ViewHolder viewHolder = (ViewHolder) convertView.getTag();
            viewHolder.mPosition = position;
            return viewHolder;
        }
    }

    public View getConvertView() {
        return mConvertView;
    }

    public <T extends View> T getView(int resId) {
        View view = mViews.get(resId);
        if (view == null) {
            view = mConvertView.findViewById(resId);
            mViews.put(resId, view);
        }
        return (T) view;
    }

    public ViewHolder setText(int resId, String text) {
        TextView textView = getView(resId);
        textView.setText(text);
        return this;
    }

    public ViewHolder setText(int resId, int textResId) {
        TextView textView = getView(resId);
        textView.setText(textResId);
        return this;
    }

    public ViewHolder setImageResource(int resId, int bgResId) {
        ImageView imageView = getView(resId);
        imageView.setImageResource(bgResId);
        return this;
    }

}
